package models

import (
	"github.com/gin-gonic/gin"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"os"
	"strings"
	"time"
)

var db *gorm.DB

//初始化所有的模型
func init() {
	db = GetDb()
	err := db.AutoMigrate(&Product{}, &Order{})
	if err != nil {
		panic(err)
	}

	product := Product{}
	db.First(&product)
	if product.ID == 0 || os.Getenv(gin.EnvGinMode) != gin.ReleaseMode{
		_ = db.Delete(&product)
		picsPrefix := "/static/products/pics/"
		var xmlyPics [] string
		xmlyPics = append(xmlyPics, picsPrefix + "/xmly/main1.jpg")
		//var xmlyPics [] string
		//xmlyPics = append(xmlyPics, picsPrefix + "/xmly/main1.jpg")
		//var xmlyPics [] string
		//xmlyPics = append(xmlyPics, picsPrefix + "/xmly/main1.jpg")
		//var xmlyPics [] string
		//xmlyPics = append(xmlyPics, picsPrefix + "/xmly/main1.jpg")
		//var xmlyPics [] string
		//xmlyPics = append(xmlyPics, picsPrefix + "/xmly/main1.jpg")
		//var xmlyPics [] string
		//xmlyPics = append(xmlyPics, picsPrefix + "/xmly/main1.jpg")
		//初始化商品信息
		var products = []Product{
			{Title: "喜马拉雅VIP巅峰会员卡1个月", Price: 10, Value: 20, Description: picsPrefix + "xmly/xmly_desc.jpg", Name: "喜马拉雅VIP巅峰会员卡1个月", Pics: strings.Join(xmlyPics, ",")},
			//{Title: "腾讯视频会员月卡", Price: 18.75, Value: 25, Description: "腾讯视频会员月卡", Name: "腾讯视频会员月卡"},
			//{Title: "爱奇艺黄金会员月卡", Price: 18.75, Value: 25, Description: "爱奇艺黄金会员月卡", Name: "爱奇艺黄金会员月卡"},
			//{Title: "爱奇艺星钻会员月卡", Price: 18.75, Value: 25, Description: "爱奇艺星钻会员月卡", Name: "爱奇艺星钻会员月卡"},
			//{Title: "优酷黄金会员月卡", Price: 18.75, Value: 25, Description: "优酷黄金会员月卡", Name: "优酷黄金会员月卡"},
			//{Title: "搜狐视频黄金会员月卡", Price: 18.75, Value: 25, Description: "搜狐视频黄金会员月卡", Name: "搜狐视频黄金会员月卡"},
			//{Title: "哔哩哔哩大会员月卡", Price: 18.75, Value: 25, Description: "哔哩哔哩大会员月卡", Name: "哔哩哔哩大会员月卡"},
			//{Title: "酷喵影视会员卡1个月", Price: 18.75, Value: 25, Description: "keep会员卡", Name: "酷喵影视会员卡1个月"},
		}
		db.CreateInBatches(&products, len(products))
	}
}

func GetDb() *gorm.DB {
	if db != nil {
		return db
	}
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second, // 慢 SQL 阈值
			LogLevel:      logger.Info, // Log level
			Colorful:      false,       // 禁用彩色打印
		},
	)
	dialector := sqlite.Open("./data/gorm.db")
	//dialector:=mysql.Open(config.AppConfig.MySqlDsn)
	db, err := gorm.Open(dialector, &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			TablePrefix: "t_",
		},
		Logger:      newLogger,
		PrepareStmt: true,
	})
	if err != nil {
		panic(err)
	}
	return db
}
